package it.omnisong.server.index;

import it.omnisong.server.persistence.dao.SongDAO;
import it.omnisong.server.persistence.postgres.PostgresException;
import it.omnisong.client.model.Song;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class LyricIndexer {
	
	private FSDirectory dir;
	private IndexWriter writer;
	private List<Song> queue = null;
	private Analyzer analyzer;
	private String indexDir = "war/omnisonggwt/index/lyrics";
	
	public LyricIndexer() throws IOException {
	    this.dir = FSDirectory.open(new File(this.indexDir));
	    this.analyzer = new StandardAnalyzer(Version.LUCENE_30);
	}
	
	public static void main(String[] args){
		
		try{
			LyricIndexer dbi = new LyricIndexer();
			dbi.indexDB();
		}catch(Exception e){
			e.printStackTrace();
		}
		/*
		try{
			DBIndexer dbi=new DBIndexer(indexPath);
			// dbi.indexDBwithoutConnection();
		}catch(Exception f){
				f.printStackTrace();
			
		}
		*/
	}
	
	/**
	 * solo per testare se funziona (no connessione a Postgres)
	 * @throws IOException 
	 * @throws LockObtainFailedException 
	 * @throws CorruptIndexException 
	 */
	
	public void indexDB() throws IOException, PostgresException{
		
		/* mi crea un nuovo indice o sovrascrive quello esistente */
	    this.writer = new IndexWriter(this.dir, this.analyzer,
	    							  true, IndexWriter.MaxFieldLength.LIMITED); 
		this.retrieveWikilinksFromDB();
		
		for (Song song : this.queue){
			String title=song.getTitle();
			String lyric=song.getLyric();
			String artist=song.getArtist();
			
			//inizio indicizzazione
			Document doc=new Document();
			doc.add(new Field("title",title,Field.Store.YES,
						Field.Index.ANALYZED));
			doc.add(new Field("artist",artist,Field.Store.YES,
						Field.Index.ANALYZED));
			doc.add(new Field("lyric",lyric,Field.Store.YES,
						Field.Index.ANALYZED));
			try{
				writer.addDocument(doc);
			}
			catch(Exception f){
					f.printStackTrace();
			}
					
			}
			int numDocs=writer.numDocs();
			
			System.out.println(numDocs+" lyrics added to the index!");
			
			//close the index
			this.closeWriter();

	}
	
	/* recupera tutti le lyrics inserite nel database */
	private void retrieveWikilinksFromDB() throws PostgresException {
	    
		SongDAO songDao = new SongDAO();
		try{
			this.queue = songDao.getAll();
		}
		catch(PostgresException e) {
			throw e;
		}
	}
	
	/* chiude l'indice */
	public void closeWriter() throws IOException {
	    this.writer.optimize();
	    this.writer.close();
	}

}
